package main

import (
	"encoding/json"
	"time"
)

type Result struct {
	Cost   int         `json:"cost_ms"`
	OK     bool        `json:"success"`
	Desc   string      `json:"desc,omitempty"`
	Value  interface{} `json:"value,omitempty"`
	err    error
	code   int
	action Action
	start  int64
}

func (r *Result) Finish() *Result {
	r.Cost = int((time.Now().UnixNano() - r.start) / 1000 / 1000)
	if r.Value == nil && r.err != nil {
		r.Value = r.err
	}
	return r
}

func (r *Result) WithAction(act Action) *Result {
	r.action = act
	return r
}
func (r *Result) WithDesc(desc string) *Result {
	r.Desc = desc
	return r
}
func (r *Result) WithCode(code int) *Result {
	r.code = code
	return r
}
func (r *Result) WithError(err error) *Result {
	r.OK = false
	r.err = err
	return r
}
func (r *Result) WithValue(value interface{}) *Result {
	r.OK = true
	r.Value = value
	return r
}

func (r *Result) bytes() []byte {
	b, _ := json.Marshal(r)
	return b
}
func (r *Result) String() (ret string) {
	b, _ := json.Marshal(r)
	ret = string(b)
	return
}
func NewResult() *Result {
	return &Result{start: time.Now().UnixNano()}
}

type Action string

func ParseAction(s string) Action {
	act := Action(s)
	if act != CREATE || act != DROP || act != SHOW || act != BATCH || act != PUT ||
		act != GET || act != AUTH || act != GETBYPREFIX {
		return NULL
	}
	return act
}

const (
	CREATE      = Action("create")
	DROP        = Action("drop")
	SHOW        = Action("show")
	BATCH       = Action("batch")
	PUT         = Action("put")
	GET         = Action("get")
	NULL        = Action("null")
	AUTH        = Action("auth")
	GETBYPREFIX = Action("getbyprefix")
)
